<?php
/**
 * sfApply actions.
 *
 * @package    5seven5
 * @subpackage sfApply
 * @author     Tom Boutell, tom@punkave.com
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class BasesfApplyActions extends sfActions
{
    public function executeApply(sfRequest $request)
    {
        $this->form = $this->newForm('sfApplyApplyForm');
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter('sfApplyApply'));
            if ($this->form->isValid())
            {
                $this->form->save();
                $profile = $this->form->getObject();
                $this->getUser()->signIn(sfGuardUserPeer::retrieveByPK($profile->getUserId()));
                $this->getUser()->setFlash('registration_success', 'Вітаємо, '.$profile->getFullName().', Ви успішно зареєстровані в системі. ');
                $this->redirect('@homepage');
            }
        }
    }
	 
    public function executeResetRequest(sfRequest $request)
    {
            $user = $this->getUser();
            if ($user->isAuthenticated())
            {
                    $guardUser = $this->getUser()->getGuardUser();
                    $this->forward404Unless($guardUser);
                    return $this->resetRequestBody($guardUser);
            }
            else
            {
                    $this->form = $this->newForm('sfApplyResetRequestForm');
                    if ($request->isMethod('post'))
                    {
                            $this->form->bind($request->getParameter('sfApplyResetRequest'));
                            if ($this->form->isValid())
                            {
                                    $user = sfGuardUserPeer::retrieveByUsername($this->form->getValue('username'));
                                    //ToDo:  make separated action for user activate deleted account
                                    if (!$user){
                                            $user = sfGuardUserPeer::retrieveNaByUsername($this->form->getValue('username'));
                                            return $this->restoreRequestBody($user);
                                    }
                                    return $this->resetRequestBody($user);
                            }
                    }
            }
    }
	
	public function executeDeleteRequest(sfRequest $request)
	{
		$user = $this->getUser();
		if ($user->isAuthenticated())
		{
			$guardUser = $this->getUser()->getGuardUser();
			$this->forward404Unless($guardUser);
			$guardUser->setIsActive(false);
			$guardUser->save();
			$this->getUser()->signOut();
			$this->getUser()->setAuthenticated(false);
			$this->getUser()->shutdown();
			return 'Account'; 			
		} else {
			return $this->redirect('@homepage');
		}
	}

    public function restoreRequestBody($user)
    {
		$this->forward404Unless($user);

		$profile = $user->getProfile();
		$profile->setValidate('n' . self::createGuid());
		$profile->save();

        /*
		$to_address = $profile->getEmail();	
		//$from_address = array('email' => 'someemail@provider.com', 'fullname' => 'SenderName');
		$from_address = array();		
		$mailContext = array('name' => $profile->getFullname(), 'validate' => $profile->getValidate());
		$subject = sfConfig::get('app_sfApplyPlugin_reset_subject',sfContext::getInstance()->getI18N()->__("Please verify your password reset request on %1%", array('%1%' => $this->getRequest()->getHost())));

		$mailer = new bsMailer();
		$mailSent = $mailer->sendBsMail(
		        $to_address,
				$from_address,
				$subject,
				array('text/html'  =>$this->getPartial('sfApply/', $mailContext),
        		      'text/plain' =>$this->getPartial('sfApply/Text', $mailContext))
				);							
				
		if (!$mailSent)
		{
			sfContext::getInstance()->getUser()->setFlash('error', sfContext::getInstance()->getI18N()->__('A server problem occured while attempting to send your message. Please try Register later.'));
			return 'MailerError';
		} else {
			sfContext::getInstance()->getUser()->setFlash('notice', sfContext::getInstance()->getI18N()->__('Mail has been sent to %address%', array('%address%' => $to_address)));
		}
		*/

        //Sending e-mail notification BEGIN
        sfLoader::loadHelpers(array('Url', 'Tag'));

        $to_address = $profile->getEmail();
        $validate = $profile->getValidate();
        $culture = $profile->getLanguage()->getName();

        $email_template = EmailTranslationPeer::get_translation_by_name("verify_password_reset_request");
        $email_template->clear_filter();
        $email_template->add_filter("%HOST_NAME%",$this->getRequest()->getHost());
        $email_template->add_filter("%CHANGE_PASSWORD_LINK%", link_to(url_for("sfApply/confirm?validate=$validate", true), "sfApply/confirm?validate=$validate", array("absolute" => true)) );
        $html_text = $email_template->get_filtered_html($culture);
        $plain_text = $email_template->get_filtered_plain($culture);
        $mailContext = array();
        $mailContext['text/html'] = $html_text;
        $mailContext['text/plain'] = $plain_text;
        $subject = $email_template->get_filtered_subject($culture);

        EmailSender::sendEmail($to_address, $subject, $mailContext);
        //Sending e-mail notification END

		return 'After';    	
    }	
	
	public function resetRequestBody($user)
	{
		$this->forward404Unless($user);

		$profile = $user->getProfile();
		$profile->setValidate('r' . self::createGuid());
		$profile->save();
        /*
		$to_address = $profile->getEmail();
		//$from_address = array('email' => 'someemail@provider.com', 'fullname' => 'SenderName');
		$from_address = array();		
		$mailContext = array('name' => $profile->getFullname(), 'validate' => $profile->getValidate());
		$subject = sfConfig::get('app_sfApplyPlugin_reset_subject',sfContext::getInstance()->getI18N()->__("Please verify your password reset request on %1%", array('%1%' => $this->getRequest()->getHost())));

		$mailer = new bsMailer();
		$mailSent = $mailer->sendBsMail(
		        $to_address,
				$from_address,
				$subject,
				array('text/html'  =>$this->getPartial('sfApply/sendValidateReset', $mailContext),
        		      'text/plain' =>$this->getPartial('sfApply/sendValidateResetText', $mailContext))
				);							
				
		if (!$mailSent)
		{
			sfContext::getInstance()->getUser()->setFlash('error', sfContext::getInstance()->getI18N()->__('A server problem occured while attempting to send your message. Please try Register later.'));
			return 'MailerError';
		} else {
			sfContext::getInstance()->getUser()->setFlash('notice', sfContext::getInstance()->getI18N()->__('Mail has been sent to %address%', array('%address%' => $to_address)));
		}
		*/
        //Sending e-mail notification BEGIN
        sfLoader::loadHelpers(array('Url', 'Tag'));

        $to_address = $profile->getEmail();
        $validate = $profile->getValidate();
        $culture = $profile->getLanguage()->getName();

        $email_template = EmailTranslationPeer::get_translation_by_name("verify_password_reset_request");
        $email_template->clear_filter();
        $email_template->add_filter("%HOST_NAME%",$this->getRequest()->getHost());
        $email_template->add_filter("%CHANGE_PASSWORD_LINK%", link_to(url_for("sfApply/confirm?validate=$validate", true), "sfApply/confirm?validate=$validate", array("absolute" => true)) );
        $html_text = $email_template->get_filtered_html($culture);
        $plain_text = $email_template->get_filtered_plain($culture);
        $mailContext = array();
        $mailContext['text/html'] = $html_text;
        $mailContext['text/plain'] = $plain_text;
        $subject = $email_template->get_filtered_subject($culture);

        EmailSender::sendEmail($to_address, $subject, $mailContext);
        //Sending e-mail notification END

		return 'After';
	}



	public function executeConfirm(sfRequest $request)
	{
		$validate = $this->request->getParameter('validate');
		$c = new Criteria();
		// 0.6.3: oops, this was in sfGuardUserProfilePeer in my application
		// and therefore never got shipped with the plugin until I built
		// a second site and spotted it!
		$c->add(sfGuardUserProfilePeer::VALIDATE, $validate);
		$c->addJoin(sfGuardUserPeer::ID, sfGuardUserProfilePeer::USER_ID);
		$sfGuardUser = sfGuardUserPeer::doSelectOne($c);
		if (!$sfGuardUser)
		{
			return 'Invalid';
		}
		$type = self::getValidationType($validate);
		if (!strlen($validate))
		{
			return 'Invalid';
		}
		$profile = $sfGuardUser->getProfile();
		$profile->setValidate(null);
		$profile->save();
		if ($type == 'New')
		{
			$sfGuardUser->setIsActive(true);
			$sfGuardUser->save();
			$this->getUser()->signIn($sfGuardUser);
		}
		if ($type == 'Reset')
		{
			$this->getUser()->setAttribute('sfApplyReset', $sfGuardUser->getId());
			return $this->redirect('sfApply/reset');
		}
	}

	public function executeReset(sfRequest $request)
	{
		$this->form = $this->newForm('sfApplyResetForm');
		if ($request->isMethod('post'))
		{
			$this->form->bind($request->getParameter('sfApplyReset'));
			if ($this->form->isValid())
			{
				$this->id = $this->getUser()->getAttribute('sfApplyReset', false);
				$this->forward404Unless($this->id);
				$this->sfGuardUser = sfGuardUserPeer::retrieveByPk($this->id);
				$this->forward404Unless($this->sfGuardUser);
				$sfGuardUser = $this->sfGuardUser;
				$sfGuardUser->setPassword($this->form->getValue('password'));
				$sfGuardUser->save();
				$this->getUser()->signIn($sfGuardUser);
				$this->getUser()->setAttribute('sfApplyReset', null);
				return 'After';
			}
		}
	}

	public function executeResetCancel()
	{
		$this->getUser()->setAttribute('sfApplyReset', null);
		return $this->redirect('@homepage');
	}

  public function executeSettings(sfRequest $request)
  {
    if($this->getUser()->hasGroup('stores') || $this->getUser()->hasGroup('chains')){
      $this->another_manager_existence = count($this->getUser()->getStore()->getStoreManagers()) > 1;
    }
    // sfApplySettingsForm inherits from sfApplyApplyForm, which
    // inherits from sfGuardUserProfile. That minimizes the amount
    // of duplication of effort. If you want, you can use a different
    // form class. I suggest inheriting from sfApplySettingsForm and
    // making further changes after calling parent::configure() from
    // your own configure() method.

    $profile = $this->getUser()->getProfile();
    $this->form = $this->newForm('sfApplySettingsForm', $profile);
    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('sfApplySettings'));
      if ($this->form->isValid())
      {
        $this->form->save();
        return $this->redirect('@homepage');
      }
    }
  }

	static private function createGuid()
	{
		$guid = "";
		// This was 16 before, which produced a string twice as
		// long as desired. I could change the schema instead
		// to accommodate a validation code twice as big, but
		// that is completely unnecessary and would break
		// the code of anyone upgrading from the 1.0 version.
		// Ridiculously unpasteable validation URLs are a
		// pet peeve of mine anyway.
		for ($i = 0; ($i < 8); $i++) {
			$guid .= sprintf("%02x", mt_rand(0, 255));
		}
		return $guid;
	}

	static private function getValidationType($validate)
	{
		$t = substr($validate, 0, 1);
		if ($t == 'n')
		{
			return 'New';
		}
		elseif ($t == 'r')
		{
			return 'Reset';
		}
		else
		{
			return sfView::NONE;
		}
	}



	// A convenience method to instantiate a form of the
	// specified class... unless the user has specified a
	// replacement class in app.yml. Sweet, no?
	protected function newForm($className, $object = null)
	{
		$key = "app_sfApplyPlugin_$className" . "_class";
		$class = sfConfig::get($key,
		$className);
		if ($object !== null)
		{
			return new $class($object);
		}
		return new $class;
	}
}
